package com.divemotor.ventarepuestosinternet.util.converter;

import java.io.Serializable;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import org.apache.log4j.Logger;
import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;
import org.springframework.stereotype.Component;

import com.divemotor.ventarepuestosinternet.model.Sucursal;
import com.divemotor.ventarepuestosinternet.validator.UsuarioClienteValidator;

@Component("sucursalConverter")
public class SucursalConverter implements Converter, Serializable {

	private static final long serialVersionUID = -3204142152236267913L;
	private static final Logger logger =  Logger.getLogger(UsuarioClienteValidator.class);
	
	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
		logger.info("getAsObject");
		return getObjectFromUIPickListComponent(component, submittedValue);
	}
	
	@SuppressWarnings("unchecked")
	private Sucursal getObjectFromUIPickListComponent(UIComponent component, String value) {
		
		final DualListModel<Sucursal> dualList;
		try {
			dualList 		  = (DualListModel<Sucursal>) ((PickList) component).getValue();
			Sucursal sucursal = getObjectFromList(dualList.getSource(), Integer.valueOf(value));
			if (sucursal == null) {
				sucursal = getObjectFromList(dualList.getTarget(), Integer.valueOf(value));
			}

			return sucursal;
		} catch (ClassCastException cce) {
			throw new ConverterException();
		} catch (NumberFormatException nfe) {
			throw new ConverterException();
		}
	}

	private Sucursal getObjectFromList(final List<?> list, final Integer identifier) {
		for (final Object object : list) {
			final Sucursal sucursal = (Sucursal) object;
			if (sucursal.getIdSucursal().equals(identifier)) {
				return sucursal;
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		if (value == null) {
            return null;
        } else {
            return ((Sucursal) value).getIdSucursal().toString();
        }
	}

}
